package com.jzy.service.impl;

import com.jzy.dto.Types;
import com.jzy.entity.Bo.StatisticsBo;
import com.jzy.entity.Vo.CommentVo;
import com.jzy.entity.Vo.ContentVo;
import com.jzy.repository.AttachVoRepository;
import com.jzy.repository.CommentRepository;
import com.jzy.repository.ContentRepository;
import com.jzy.repository.MetaRepository;
import com.jzy.service.ISiteService;
import com.jzy.util.PredicateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class SiteServiceImpl implements ISiteService {

    @Resource
    private CommentRepository commentRepository;

    @Resource
    private ContentRepository contentRepository;
    
    @Resource
    private MetaRepository metaRepository;
    
    @Resource
    private AttachVoRepository attachVoRepository;

    private static final Logger LOGGER = LoggerFactory.getLogger(SiteServiceImpl.class);

    @Override
    public List<CommentVo> recentComments(int limit) {
        LOGGER.debug("Enter recentComments method:limit={}", limit);
        if (limit < 0 || limit > 10) {
            limit = 10;
        }
        PageRequest of = getPageRequest(limit);
        Page<CommentVo> all = commentRepository.findAll(of);
        return all.getContent();
    }

    private PageRequest getPageRequest(int limit) {
        ArrayList<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.DESC, "created"));
        Sort by = Sort.by(orders);
        return PageRequest.of(0, limit, by);
    }

    @Override
    public List<ContentVo> recentContents(int limit) {
        LOGGER.debug("Enter recentContents method");
        if (limit < 0 || limit > 10) {
            limit = 10;
        }
        Specification<ContentVo> specification = PredicateUtil.getContentVoSpecification();
        PageRequest of = getPageRequest(limit);
        return contentRepository.findAll(specification, of).getContent();
    }

    @Override
    public StatisticsBo getStatistics() {
        LOGGER.debug("Enter getStatistics method");
        StatisticsBo statistics = new StatisticsBo();
        long comments = commentRepository.count();
        long articles = contentRepository.count();
        long links = metaRepository.count();
        long attaches = attachVoRepository.count();
        statistics.setArticles(articles);
        statistics.setComments(comments);
        statistics.setAttaches(attaches);
        statistics.setLinks(links);
        LOGGER.debug("Exit getStatistics method");
        return statistics;
    }
}
